<?php

namespace App\Controller;

use Swoole;

class Db extends Swoole\Controller {

	public function apt_test() {
		$apt = new Swoole\SelectDB($this->db);
		$apt->from('users');
		$apt->equal('id', 1);
		$res = $apt->getall();
		var_dump($res);
	}

	public function tables() {
		// $this->db->debug = true; // 开启Debug。
		/**
		 * master database
		 */
		$tables = $this->db->query("show tables")->fetchall();
		var_dump($tables);
		
		/**
		 * other
		 */
// 		$tables = $this->db("huya")->query("show tables")->fetchall();
// 		var_dump($tables);
	}

	public function put() {
		$model = Model('User');
		$id = $model->put(array(
				'username'   => uniqid('winer_'),
				'email'      => uniqid('winer_') . '@qq.com',
				'created_at' => date('Y-m-d H:i:s'),
				'updated_at' => date('Y-m-d H:i:s')
		));
		echo "insert id = $id\n";
	}

	public function get() {
		$model = Model('User');
		$user = $model->get(1);
		/**
		 * 打印数组
		 */
		var_dump($user->get());
		/**
		 * 修改mobile 为 13800008888
		 */
		$user->updated_at = date('Y-m-d H:i:s');
		$user->save();

		// 删除此条记录
		// $user->delete();
	}
	
	/**
	 * 原生SQL查询支持。
	 */
	public function native_sql() {
		$sql = "SELECT * FROM winer_users WHERE email LIKE 'winer%'";
		$list = $this->db->query($sql)->fetchall();
		print_r($list);
	}

	public function gets() {
		$model = Model('User');

		$gets = array();
		$gets['email'] = 5;

		// 仅获取数据
		// var_dump($model->gets($gets));

		// 分页
		$gets['page'] = empty($_GET['page']) ? 1 : intval($_GET['page']);
		$gets['pagesize'] = 5;
		$pager = null;
		$list = $model->gets($gets, $pager);
		
		foreach ($list as $li) {
			echo "{$li['id']}: {$li['name']}<br/>\n";
		}
		// 上一页/下一页
		echo $pager->render();
	}
}